package cn.charmaine.org.service.impl;

import cn.charmaine.basic.Exception.CustomException;
import cn.charmaine.basic.util.MD5Utils;
import cn.charmaine.basic.util.StrUtils;
import cn.charmaine.org.domain.Employee;
import cn.charmaine.org.domain.Logininfo;
import cn.charmaine.org.domain.User;
import cn.charmaine.org.domain.dto.SmsCodeParam;
import cn.charmaine.org.mapper.LogininfoMapper;
import cn.charmaine.org.mapper.UserMapper;
import cn.charmaine.org.service.IUserService;
import cn.charmaine.basic.base.service.impl.BaseServiceImpl;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xmy
 * @since 2022-07-09
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public User queryByUsername(String phone) {
        return userMapper.selectByUsername(phone);
    }

    @Override
    @Transactional
    public void register(SmsCodeParam param) {
        String phoneOrEmail=param.getPhone();
        if (StringUtils.isEmpty(phoneOrEmail)){
            phoneOrEmail=param.getEmail();
        }

        //1. 参数非空校验
        if(StringUtils.isEmpty(phoneOrEmail)||
                StringUtils.isEmpty(param.getSmsCode())||
                StringUtils.isEmpty(param.getPassword())||
                StringUtils.isEmpty(param.getConfirmPassword())
        ){
            throw new CustomException("参数异常");
        }
        //2.两次密码是否输入一致
        if(!param.getPassword().equals(param.getConfirmPassword())){
            throw new CustomException("两次密码不一样，请重新输入");
        }
        //3.校验用户是否存在
        User user = userMapper.selectByUsername(phoneOrEmail);
        if(user != null){
            throw new CustomException("用户已存在");
        }
        //4.校验短信验证码是否存在(或者邮箱验证码是否存在)
        Object smsCodeValue = redisTemplate.opsForValue().get("register:" + phoneOrEmail);
        //短信验证码不存在
        if(smsCodeValue == null){
            throw new CustomException("验证码已过期，请重新发送！");
        }
        //短信验证码存在
        String[] split = smsCodeValue.toString().split(":");
        //验证码是否正确(忽略大小写比较)
        if(!split[0].equalsIgnoreCase(param.getSmsCode())){
            throw new CustomException("验证码错误！");
        }
        //5.密码MD5加密，记录盐值
        String salt = StrUtils.getComplexRandomString(32);
        //给密码加密
        String md5Password = MD5Utils.encrypByMd5(param.getPassword() + salt);
        //6.先设置默认值，再保存信息
        User newUser = dto2User(phoneOrEmail,param,salt,md5Password);
        Logininfo logininfo = user2Logininfo(newUser);
        //调用方法保存信息
        logininfoMapper.insert(logininfo);
        newUser.setLogininfoId(logininfo.getId());
        userMapper.insert(newUser);

    }

    private User dto2User(String phoneOrEmail,SmsCodeParam param, String salt, String md5Password) {
        User user = new User();
        user.setUsername(phoneOrEmail);
        user.setEmail(param.getEmail());
        user.setPhone(param.getPhone());
        user.setSalt(salt);
        user.setPassword(md5Password);
        user.setState(1);
        user.setCreatetime(new Date());
        return user;
    }

    private Logininfo user2Logininfo(User newUser) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(newUser,logininfo);
        logininfo.setDisable(1);
        logininfo.setType(1);
        return logininfo;
    }
}
